package com.jy.books.service.impl;

import java.util.List;

import com.jy.records.domain.BorrowRecords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.jy.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.jy.books.mapper.BooksMapper;
import com.jy.books.domain.Books;
import com.jy.books.service.IBooksService;

/**
 * 图书管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class BooksServiceImpl implements IBooksService 
{
    @Autowired
    private BooksMapper booksMapper;

    /**
     * 查询图书管理
     * 
     * @param bookId 图书管理主键
     * @return 图书管理
     */
    @Override
    public Books selectBooksByBookId(Long bookId)
    {
        return booksMapper.selectBooksByBookId(bookId);
    }

    /**
     * 查询图书管理列表
     * 
     * @param books 图书管理
     * @return 图书管理
     */
    @Override
    public List<Books> selectBooksList(Books books)
    {
        return booksMapper.selectBooksList(books);
    }

    /**
     * 新增图书管理
     * 
     * @param books 图书管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBooks(Books books)
    {
        int rows = booksMapper.insertBooks(books);
        insertBorrowRecords(books);
        return rows;
    }

    /**
     * 修改图书管理
     * 
     * @param books 图书管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBooks(Books books)
    {
        booksMapper.deleteBorrowRecordsByBookId(books.getBookId());
        insertBorrowRecords(books);
        return booksMapper.updateBooks(books);
    }

    /**
     * 批量删除图书管理
     * 
     * @param bookIds 需要删除的图书管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBooksByBookIds(Long[] bookIds)
    {
        booksMapper.deleteBorrowRecordsByBookIds(bookIds);
        return booksMapper.deleteBooksByBookIds(bookIds);
    }

    /**
     * 删除图书管理信息
     * 
     * @param bookId 图书管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBooksByBookId(Long bookId)
    {
        booksMapper.deleteBorrowRecordsByBookId(bookId);
        return booksMapper.deleteBooksByBookId(bookId);
    }

    /**
     * 新增借阅记录信息
     * 
     * @param books 图书管理对象
     */
    public void insertBorrowRecords(Books books)
    {
        List<BorrowRecords> borrowRecordsList = books.getBorrowRecordsList();
        Long bookId = books.getBookId();
        if (StringUtils.isNotNull(borrowRecordsList))
        {
            List<BorrowRecords> list = new ArrayList<BorrowRecords>();
            for (BorrowRecords borrowRecords : borrowRecordsList)
            {
                borrowRecords.setBookId(bookId);
                list.add(borrowRecords);
            }
            if (list.size() > 0)
            {
                booksMapper.batchBorrowRecords(list);
            }
        }
    }
}
